package com.liao.note.controller;

import com.liao.note.domain.Note;
import com.liao.note.enums.ResultCode;
import com.liao.note.service.NoteService;
import com.liao.note.util.AsyncUtil;
import com.liao.note.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;

@RestController
@RequestMapping("/note")
public class NoteController {

    @Autowired
    private NoteService noteService;
    @Autowired
    private AsyncUtil asyncUtil;

    @RequestMapping(value = "/list/{userId}", method = RequestMethod.GET)
    public ResultVO<Object> queryNoteList(@PathVariable("userId") Integer userId) {
        ArrayList<Note> notes = noteService.queryByUserId(userId);
        return new ResultVO<>(notes);
    }

    @RequestMapping(value = "/findByCategoryId/{categoryId}", method = RequestMethod.GET)
    public ResultVO<Object> queryList(@PathVariable("categoryId") Integer categoryId) {
        return new ResultVO<>(noteService.queryByCategoryId(categoryId));
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ResultVO<Object> addNote(@RequestBody Note note) {
        int i = noteService.addNote(note);
        return new ResultVO<>(ResultCode.SUCCESS);
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public ResultVO<Object> updateNote(@RequestBody Note note) {
        int i = noteService.updateNote(note);
        return new ResultVO<>(ResultCode.SUCCESS);
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public ResultVO<Object> deleteNote(@PathVariable("id") Integer id) {
        int i = noteService.deleteById(id);
        return new ResultVO<>(ResultCode.SUCCESS);
    }

    @RequestMapping(value = "/deleteAll/{userId}", method = RequestMethod.GET)
    public ResultVO<Object> deleteAllNote(@PathVariable("userId") Integer userId) {
        boolean b = noteService.deleteAllNote(userId);
        return new ResultVO<>(ResultCode.SUCCESS);
    }

    @RequestMapping(value = "/recycle/list/{userId}", method = RequestMethod.GET)
    public ResultVO<Object> recycleList(@PathVariable("userId") Integer userId) {
        return new ResultVO<>(noteService.queryDeleteByUserId(userId));
    }

    @RequestMapping(value = "/share/list/{userId}", method = RequestMethod.GET)
    public ResultVO<Object> shareList(@PathVariable("userId") Integer userId) {
        return new ResultVO<>(noteService.queryAllShare(userId));
    }

    @RequestMapping(value = "/uploadAudio/{userId}", method = RequestMethod.POST)
    public ResultVO<Object> uploadFile(@RequestParam("file") MultipartFile[] multipartFiles, @PathVariable("userId") Integer userId) {
        System.out.println(multipartFiles.length);
        ArrayList<File> files = new ArrayList<>();
        for (MultipartFile multipartFile : multipartFiles) {
            String name = multipartFile.getOriginalFilename();
            name = name.replace("n", "y");
            URL resource = this.getClass().getClassLoader().getResource("static");
            if (resource == null) {
                return new ResultVO<>(ResultCode.ERROR);
            }
            String filePath = resource.getPath() + "/audio/";
            File fileDirectory = new File(filePath);
            if (!fileDirectory.exists()) {
                fileDirectory.mkdir();
            }
            File file = new File(filePath + name);
            try {
                multipartFile.transferTo(file);
                files.add(file);
            } catch (IOException e) {
                e.printStackTrace();
                return new ResultVO<>(ResultCode.ERROR, e.getMessage());
            }
        }
        asyncUtil.changeAudio(files, userId);
        return new ResultVO<>(ResultCode.SUCCESS, "上传成功");
    }

    @RequestMapping(value = "/downLoadAudio/{audioName}", method = RequestMethod.POST)
    public ResultVO<Object> downLoadAudio(HttpServletRequest request, HttpServletResponse response, @PathVariable("audioName") String audioName) throws IOException {
        ServletOutputStream os = response.getOutputStream();
        URL resource = this.getClass().getClassLoader().getResource("static");
        if (resource == null) {
            return new ResultVO<>(ResultCode.ERROR, "服务器异常");
        }
        File file = new File(resource.getPath() + "/audio/" + audioName);
        if (!file.exists()) {
            return new ResultVO<>(ResultCode.REQUEST_ERROR, "音频不存在");
        }
//        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name, "utf-8"));
        //如果单纯写这个也可以进行下载功能，表示以二进制流的形式
        response.setContentType("application/octet-stream");
        FileInputStream fis = new FileInputStream(file);
        byte[] b = new byte[1024];
        int len;
        while ((len = fis.read(b)) > -1) {
            os.write(b, 0, len);
        }
        return null;
    }

}
